<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="采购人" prop="purchaser">
        <el-input
          v-model="queryParams.purchaser"
          placeholder="请输入采购人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="采购时间" prop="poDatetime">-->
      <!--        <el-date-picker clearable size="small" style="width: 200px"-->
      <!--                        v-model="queryParams.poDatetime"-->
      <!--                        type="date"-->
      <!--                        value-format="yyyy-MM-dd"-->
      <!--                        placeholder="选择采购时间">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['medicine:purchaseOrder:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['medicine:purchaseOrder:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['medicine:purchaseOrder:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['medicine:purchaseOrder:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table fit v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="采购人" align="center" prop="purchaser"/>

      <el-table-column label="采购时间" align="center" prop="poDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.poDatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="poPrice"/>
      <el-table-column label="备注" align="center" prop="poDesc"/>
      <el-table-column label="收据图片" align="center" prop="poImageUrl" min-width="240px">
        <template slot-scope="scope">
            <span v-for="item in scope.row.poImageUrl" >
              <el-image
                :preview-src-list="[item]"
                style="width: 80px; height: 80px"
                :src="item"
                :fit="fit"/>
            </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="gmtModified" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtModified, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="poCreator"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medicine:purchaseOrder:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['medicine:purchaseOrder:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :layout="'total,prev,pager,next,sizes'"

      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-form-item label="采购人" prop="purchaser">
          <el-input v-model="form.purchaser" placeholder="请输入采购人"/>
        </el-form-item>
        <el-form-item label="采购时间" prop="poDatetime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.poDatetime"
                          type="date"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          placeholder="选择采购时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="药品清单" label-width="50px">
          <!--          <medicine-select unit="千克" :list="medicineList" @listChange="listChange" @input="listChange"></medicine-select>-->
          <div class="input-group" v-for="(item,index) in medicineInfoInputList">
            <el-select @change="medicineChange" filterable v-model="item.medId" style="width: 40%;margin-bottom: 5px">
              <el-option
                v-for="item in medicineList"
                :key="item.medId"
                :label="item.medName"
                :value="item.medId">
                <span style="float: left">{{ item.medName }}</span>
                <span
                  style="float: right; color: #8492a6; font-size: 12px;margin-left: 10px">{{ item.marketPrice }}元/克</span>
              </el-option>
            </el-select>
            <el-input @input="getCostPriceTotal(index)" v-model="item.medWeight" placeholder="重量"
                      style="width: 38%;margin-bottom: 5px">
              <template slot="append">千克</template>
            </el-input>
            <el-input v-model="item.medCostPrice" placeholder="进价"
                      style="width: 40%">
              <template slot="append">元/克</template>
            </el-input>
            <el-input v-model="item.medMarketPrice" placeholder="售价"
                      style="width: 38%">
              <template slot="append">元/克</template>
            </el-input>

            <el-button @click="addInputGroup" type="primary" icon="el-icon-plus" size="mini"
                       circle/>
            <el-button @click="removeInputGroup(item,index)" type="danger"
                       icon="el-icon-minus" size="mini" circle style="margin-left: 0"/>
          </div>

        </el-form-item>
        <el-form-item label="实际价格" prop="poPrice">
          <el-input v-model="form.poPrice" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="备注" prop="poDesc">
          <el-input type="textarea" rows="3" :maxlength="200" show-word-limit v-model="form.poDesc"
                    placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="收据图片" prop="poImageUrl">
          <image-upload @upload-success="imageUploadSuccess"></image-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <div class="price">
          <span>金额: </span>
          <count-to :start-val="oldPrice" :end-val="totalPrice" prefix="¥" :decimals="2" :duration="1000"
                    class="text-danger"/>
        </div>

        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addPurchaseOrder,
    delPurchaseOrder,
    exportPurchaseOrder,
    getPurchaseOrder,
    listPurchaseOrder,
    updatePurchaseOrder
  } from '@/api/medicine/purchaseOrder'
  import MedicineSelect from '../../../components/MedicineSelect'
  import ImageUpload from '../../../components/ImageUpload'
  import CountTo from 'vue-count-to'
  import { listMedicine } from '../../../api/medicine/medicine'
  import { computePrice } from '../../../api/medicine/prescription'
  import { computeCostPriceTotal } from '../../../api/medicine/purchaseOrder'

  export default {
    name: 'PurchaseOrder',
    components: { MedicineSelect, ImageUpload, CountTo },
    data() {
      return {
        components: {
          MedicineSelect
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 采购管理表格数据
        purchaseOrderList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          purchaser: undefined,
          poDatetime: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          purchaser: [
            { required: true, message: '采购人不能为空', trigger: 'blur' }
          ],
          poPrice: [
            { required: true, message: '价格不能为空', trigger: 'blur' }
          ]
        },

        medicineInfoInputList: [{ medId: '', medWeight: '', medCostPrice: '', medMarketPrice: '' }],
        medicineList: [],
        oldPrice: 19,
        totalPrice: 9604.23
      }
    },
    watch: {

      medicineInfoInputList: {
        handler(newValue, oldValue) {
          console.log(newValue, oldValue)
        }
      },
      deep: true
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询采购管理列表 */
      getList() {
        this.loading = true
        listPurchaseOrder(this.queryParams).then(response => {
          const purchaseOrderList = response.rows
          purchaseOrderList.forEach(item => {
            item.poImageUrl = JSON.parse(item.poImageUrl)
          })
          this.purchaseOrderList = purchaseOrderList
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          poId: undefined,
          purchaser: undefined,
          poCreator: undefined,
          poDatetime: undefined,
          poPrice: undefined,
          poDesc: undefined,
          poImageUrl: undefined,
          gmtCreate: undefined,
          gmtModified: undefined,
          isDeleted: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加采购记录'
        this.getMedicineList()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {

        this.reset()
        const id = row.id || this.ids
        this.getMedicineList()
        getPurchaseOrder(id).then(response => {
          const po = response.data
          this.form = po
          this.open = true
          this.totalPrice = po.poPrice
          this.medicineInfoInputList = po.medicineList
          this.title = '修改采购'
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updatePurchaseOrder(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                }
              })
            } else {
              const data = this.form
              data.poImageUrl = JSON.stringify(data.poImageUrl)
              data.medicineList = this.medicineInfoInputList
              addPurchaseOrder(data).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除采购管理编号为"' + ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delPurchaseOrder(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有采购管理数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportPurchaseOrder(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },

      async getMedicineList() {
        this.medicineList = (await listMedicine()).rows
      },
      //todo 获取金额
      async getCostPriceTotal() {
        this.oldPrice = Number(this.totalPrice)
        const medicineList = this.medicineInfoInputList.filter(item => {
          //未选择药品,未输入克数,输入不是数字的,不参与计算
          // && !item.medGram.endsWith(".") 表示以'.'结尾的不参与计算
          return item.medWeight !== '' && !isNaN(Number(item.medWeight)) && item.medId !== ''
        })
        if (medicineList.length > 0) {
          const data = { medicineList }
          const res = await computeCostPriceTotal(data)
          this.totalPrice = Number(res.data)
        } else {
          this.totalPrice = 0
        }
      },

      medicineChange(value) {

        this.getCostPriceTotal()

      },

      addInputGroup() {
        this.medicineInfoInputList.push({ medId: '', medGram: '' })
      },
      removeInputGroup(item, index) {
        const medId = this.medicineInfoInputList[index].medId
        let medName = ''
        if (medId !== '') {
          this.medicineList.some(item => {
            if (item.medId === medId) {
              medName = ` [ ${item.medName} ] `
              return true
            }
          })
        }
        this.$confirm(`确定删除${medName}吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const list = this.medicineInfoInputList
          list.splice(index, 1)
          this.getCostPriceTotal()
        })
      },
      imageUploadSuccess(fileList) {
        this.form.poImageUrl = fileList.map(item => {
          return item.response.key
        })
      },
      async getMedicineList() {
        this.medicineList = (await listMedicine()).rows
      },

    }
  }
</script>
<style scoped>

  .price {
    position: absolute;
    left: 25px;
    bottom: 25px;
  }

  @media only screen and (max-width: 767px) {


    .input-group {

      margin-bottom: 15px;

    }

    .el-select-dropdown__item {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
    }

    .price {
      position: absolute;
      left: 25px;
      bottom: 25px;
    }
  }


</style>
